package com.imooc.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.async.DeferredResult;

import javax.servlet.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

/*
*
* 返回值是 DeferredResult 的异步处理
* */
@Controller
public class AsyncController2 {
    @ResponseBody
    @RequestMapping(value = "/deferred",produces = "text/plain; charset=UTF-8")
    public DeferredResult<String> deferredResultExam() {
    	/*第一个参数表示 超时时间
    	* 第二个参数表示 如果发生超时，返回的结果*/
        final DeferredResult<String> result = new DeferredResult<String>(7*1000L, "超时了");
        approve(result);
        return result;
    }
    private void approve(DeferredResult<String> result){
        Runnable r = new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(5 * 1000L);
                    result.setResult("同意 "+new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
        new Thread(r).start();
    }
}
